import {BadRequestException, Injectable, InternalServerErrorException, NotFoundException} from "@nestjs/common";
import {InjectRepository} from "@nestjs/typeorm";
import {BooksEntity} from "./books.entity";
import {Repository} from "typeorm";
import {PagingResponseDto} from "../../common/dto/paging.dto";
import {Neo4jDao} from "../common/database/neo4j.dao";
import {BOOK} from "../../common/constants/neo4jNode";
import {UserScoreService} from "../common/userScore/userScore.service";

@Injectable()
export class BooksService {

    constructor(
        private readonly neo4jDao: Neo4jDao,
        private readonly userScoreService: UserScoreService,
        @InjectRepository(BooksEntity) private readonly booksRepository: Repository<BooksEntity>
    ) {
    }

    /**
     * @Description: 获取图书数据，分页
     * @author zhaojiuyi
     * @date 2023/4/7
     * @param {number} pageNo 页数
     * @param {number} pageSize 页面大小
     * @return {Promise<PagingResponseDto<BooksEntity>>} 返回由图书实体组成的数组外加总数据条数
     */
    async getList(pageNo: number, pageSize: number): Promise<PagingResponseDto<BooksEntity>> {
        const result = await this.booksRepository.findAndCount({
            skip: pageNo * pageSize,
            take: pageSize
        });
        return {list: result[0], total: result[1]};
    }

    /**
     * @Description: 图书评分
     * @author zhaojiuyi
     * @date 2023/5/17
     * @param {string} userId 用户id
     * @param {string} bookId 图书id
     * @param {number} score 评分
     */
    async setScoreByBookId(userId: string, bookId: string, score: number) {
        const result = await this.neo4jDao.findNode(BOOK, {
            id: bookId
        });
        if (!result) throw new NotFoundException("bookId不存在")
        await this.userScoreService.save({bookId,userId,score})
        return "success"
    }

    /**
     * @Description: 搜索节点，根据name属性
     * @author zhaojiuyi
     * @date 2023/5/24
     * @param {string} searchValue 搜索字段
     * @param {number} size 数据长度
     * @return {any[]}
    */
    async searchNodeByName(searchValue:string,size:number):Promise<any[]>{
        const CQL = `match (n) where n.name Contains "${searchValue}" return n`
        const result = await this.neo4jDao.read(CQL,"n")
        return result.slice(0,size)
    }

    /**
     * @Description: 根据名称搜索图书
     * @author zhaojiuyi
     * @date 2023/5/24
     * @param {string} searchValue 搜索字段
     * @param {number} size 数据长度
     * @return {any[]}
    */
    async searchBookByName(searchValue:string,size:number):Promise<any[]>{
        const CQL = `match (n:${BOOK}) where n.name Contains "${searchValue}" return n`
        const result = await this.neo4jDao.read(CQL,"n")
        return result.slice(0,size)
    }


    /**
     * @Description: 统计图书数据的数量
     * @author zhaojiuyi
     * @date 2023/4/7
     * @return {Promise<number>}
     */
    async getCount(): Promise<number> {
        return await this.booksRepository.count();
    }
}
